package com.baiyue.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baiyue.model.menu.TreeNodeResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author 伍波
 * @date 2023/5/10 16:49
 */
@Component
public class MenuManager {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 递归获取菜单
     * @param jsonArray
     * @return
     */
    public List<TreeNodeResponse> getMenuList(JSONArray jsonArray) {
        return jsonArray.stream()
                .map(obj -> {
                    JSONObject jsonObject = (JSONObject) obj;
                    Integer id = jsonObject.getInteger("id");
                    String name = jsonObject.getString("name");
                    JSONArray childArray = jsonObject.getJSONArray("children");
                    List<TreeNodeResponse> childList = null;
                    if (childArray != null && !childArray.isEmpty()) {
                        childList = getMenuList(childArray);
                        if (childList.isEmpty()) {
                            childList = null;
                        }
                    }
                    return new TreeNodeResponse(id, name, childList);
                })
                .collect(Collectors.toList());
    }

    /**
     * 将二维数组转为String
     * @param menuArr
     * @return
     */
    public String menuIds(String menuArr){
        List<List<Integer>> list = JSON.parseObject(menuArr, new TypeReference<List<List<Integer>>>() {});
        Set<Integer> set = list.stream().flatMap(Collection::stream).collect(Collectors.toSet());
        List<String> strList = set.stream().map(String::valueOf).sorted().collect(Collectors.toList());
        return String.join(",", strList);
    }
}
